import { createRouter, createWebHashHistory } from 'vue-router'; // 修改为 createWebHashHistory
import MovieListView from '../views/MovieListView.vue';
import MovieAddView from '../views/MovieAddView.vue';
import MovieDetailView from '../views/MovieDetailView.vue';
import AuthView from '../views/AuthView.vue';
import MovieDetail from '../components/movie/MovieDetail.vue';

import { useUserStore } from '@/stores/user';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: MovieDetailView
  },
  {
    path: '/add-movie',
    name: 'AddMovie',
    component: MovieAddView,
    meta: { requiresAuth: true }
  },
  {
    path: '/MovieListView',
    name: 'MovieListView',
    component: MovieListView,
    meta: { requiresAuth: true }
  },
  {
    path: '/movie/:id',
    name: 'MovieDetail',
    component: MovieDetail,
    meta: { requiresAuth: false }
  },
  {
    path: '/edit-movie/:id',
    name: 'EditMovie',
    component: MovieAddView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: AuthView,
    props: { mode: 'login' },
    meta: { requiresUnauth: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: AuthView,
    props: { mode: 'register' },
    meta: { requiresUnauth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL), // 修改为 createWebHashHistory
  routes
});

// 路由守卫保持不变
router.beforeEach((to, from, next) => {
  const store = useUserStore();
  const { isLoggedIn } = store;
  
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login');
  } else if (to.meta.requiresUnauth && isLoggedIn) {
    next('/');
  } else {
    next();
  }
});

export default router;